//
//  AppDelegate.m
//  toroBracelet
//
//  Created by 丁益 on 16/7/19.
//  Copyright © 2016年 celi. All rights reserved.
//

#import "AppDelegate.h"
#import "CLControllerTool.h"
#import <CoreLocation/CoreLocation.h>
#import "CLDeviceIOS.h"
#import <AVFoundation/AVFoundation.h>
#import "CLProfileBleProtocolTool.h"
#import "CLDeviceInfo.h"
#import "CLBuleToothTool.h"
#import "CLScanBuleToothMode.h"
#import "CLProfileInfo.h"


@interface AppDelegate ()<CLBuleToothToolDelegate>
{
    CLLocationManager *locationManager;
    
}

@property (nonatomic, strong) CLBuleToothTool *buleToothTool;
@property (nonatomic, strong) CLProfileBleProtocolTool *profileBleProtocolTool;
@property (nonatomic, strong) NSTimer *readRissTime;

@end


@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // 1.创建窗口
    self.window = [[UIWindow alloc] init];
    self.window.frame = [UIScreen mainScreen].bounds;
    
    // 2.显示窗口(成为主窗口)
    [self.window makeKeyAndVisible];
    
    // 3.设置窗口的根控制器
    [CLControllerTool chooseRootViewController];
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

    [self buleToothInit];
    
    self.readRissTime = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(readRissTimeHandle:) userInfo:nil repeats:YES];
    [self startTimer];
    
    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    DLog(@"推到后台----");
    
    //蓝开蓝牙
    [self.buleToothTool cancelPeripheralConnection];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    DLog(@"进入前台----");
    
    
//    CLBuleToothTool *buleToothTool = [CLBuleToothTool sharedBuleToothTool];
//    self.buleToothTool = buleToothTool;
//    self.buleToothTool.delegate = self;
//    [self.buleToothTool connect:self.buleToothTool.connectPeripheral];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark -蓝牙处理
- (void)buleToothInit {
    
    BOOL isPeripheralflg = NO;
    //扫描蓝牙
    CLBuleToothTool *buleToothTool = [CLBuleToothTool sharedBuleToothTool];
    buleToothTool.delegate = self;
    NSArray *peripheralArray = [buleToothTool.centralManager retrieveConnectedPeripheralsWithServices:@[[CBUUID UUIDWithString:kServiceUUID]]];
    NSString *locString = [[CLProfileInfo sharedProfileInfo] uuidString];
    for (CBPeripheral *peripheral in peripheralArray) {
        if ([peripheral.identifier.UUIDString isEqualToString:locString]) {
            [buleToothTool connect:peripheral];
            buleToothTool.peripheral = peripheral;
            buleToothTool.connectPeripheral = peripheral;
            isPeripheralflg = YES;
        }
    }
    
    if ([buleToothTool isConnected]) {
        DLog(@"蓝牙已连接------");
    }
    
    
    if (isPeripheralflg == NO) {
        [buleToothTool StartScanBuleToothDevice];
    }
    self.buleToothTool = buleToothTool;
}


#pragma  CLBuleToothTool 代理
- (void)scanBuleToothDeviceWithPeripheral:(NSArray *)peripheralArray{
    
    if (peripheralArray.count < 1)  return;
    for (CBPeripheral *peripheral in peripheralArray) {
        CLScanBuleToothMode *mode = [[CLScanBuleToothMode alloc]init];
        mode.BuleToothName = peripheral.name;
        mode.peripheral = peripheral;
        DLog(@"uuid=%@",[[CLProfileInfo sharedProfileInfo] uuidString]);
        DLog(@"modeUUID = %@",mode.peripheral.identifier.UUIDString);
        
        if ([mode.peripheral.identifier.UUIDString isEqualToString:[[CLProfileInfo sharedProfileInfo] uuidString]]) {
            
            [self.buleToothTool connect:mode.peripheral];
            //结束蓝牙扫描
            [self.buleToothTool stopScanBuleToothDevice];
        }
    }
    
}



- (void)buleToothTool:(CLBuleToothTool *)buleToothTool didConnectPeripheral:(CBPeripheral *)peripheral {

    CLProfileBleProtocolTool *profileBleProtocolTool = [[CLProfileBleProtocolTool alloc]init];
    Byte userId[5] = {0x11,0x22,0x33,0x44,0x55};
    self.profileBleProtocolTool = profileBleProtocolTool;
    [self.profileBleProtocolTool sendLoginRequestWihtuserId:userId lenght:5 loginReslutBlock:^(loginResult result) {
        DLog(@"登录成功");
        [[CLDeviceInfo sharedDeviceInfo] setIsLoginDevice:YES];
    }failBlock:^{
        
    }];
    
    
}

#pragma timer

-(void)startTimer{
    
    [[NSRunLoop currentRunLoop] addTimer:self.readRissTime forMode:NSRunLoopCommonModes];
}

- (void)readRissTimeHandle:(NSTimer*)timer {
    
    if (self.buleToothTool.peripheral ) {
        [self.buleToothTool.peripheral readRSSI];
        [self.buleToothTool isDeviceConnect];
    }
//    DLog(@"RISS 定时器-------");
}

@end
